
import 'package:bip39/bip39.dart' as bip39;
import 'dart:typed_data';

import 'package:xim/common/util/sm2.dart';

class EccUtil {

  static Uint8List mnemonicToSeed(List<String> mnemonic){
    return bip39.mnemonicToSeed(mnemonic.join(''));
  }

  static List<String> generateMnemonic(){
    return bip39.generateMnemonic(strength: 128).split(" ");
  }

  static BigInt bytesToBigInt(Uint8List bytes) {
    BigInt result = BigInt.from(0);
    for (int i = 0; i < bytes.length; i++) {
      result += BigInt.from(bytes[bytes.length - i - 1]) << (8 * i);
    }
    return result;
  }

  static KeyPair generateKeyPair({BigInt? seed}){
      return SM2.generateKeyPair(seed: seed);
  }

  static String encryptHex(String msg, String publicKey,{int cipherMode = C1C3C2}){
     var res =  SM2.encrypt(msg, publicKey, cipherMode: cipherMode);
     if(!res.startsWith("04")) {
       res = "04$res";
     }
     return res;
  }

  static String decryptHex(String encryptHexData, String privateKey, {int cipherMode = C1C3C2}) {
    if(encryptHexData.startsWith("04")){
      encryptHexData = encryptHexData.substring(2);
    }
    return SM2.decrypt(encryptHexData, privateKey, cipherMode: cipherMode);
  }

  static String sign(String msg, String hexPrivateKey, {String? publicKey}){
    var res =  SM2.signature(msg, hexPrivateKey, userId: "xim", der: true, hash: true);
    return res;
  }

}